package cn.fiker.BeautyPic.worker;

import java.util.ArrayList;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

/**
 * 系统应用封装
 * @author liuqs
 *
 */
public class PackagesInfo {

	private List<ApplicationInfo> appList;
	private Context context;

	public PackagesInfo(Context context) {
		this.context = context;

		// 通包管理器，检索所有的应用程序（甚至卸载的）与数据目录
		PackageManager pm = context.getApplicationContext().getPackageManager();
		appList = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
	}

	/**
	 * 获取已经安装的应用
	 * 
	 * @return
	 */
	public ArrayList<Program> getInstalled() {
		ArrayList<Program> list = new ArrayList<Program>();
		Program current;
		for (ApplicationInfo appinfo : appList) {
			current = new Program();
			current.setPackageName(appinfo.packageName);
			current.setInstalled(true);
			current.setName(appinfo.name);
			list.add(current);
		}
		return list;
	}

	/**
	 * 获取已经安装的应用包
	 * 
	 * @return
	 */
	public ArrayList<String> getInstalledPackage() {
		ArrayList<String> list = new ArrayList<String>();
		for (ApplicationInfo appinfo : appList) {
			list.add(appinfo.packageName);
		}
		return list;
	}

	/**
	 * 获取正在运行中的应用
	 * 
	 * @return
	 */
	public List<Program> getRunningProcess() {
		ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		// 获取正在运行的应用
		List<RunningAppProcessInfo> running = activityManager.getRunningAppProcesses();
		// 获取包管理器，在这里主要通过包名获取程序的图标和程序名
		PackageManager packageManger = context.getPackageManager();
		ArrayList<Program> list = new ArrayList<Program>();

		for (RunningAppProcessInfo ra : running) {
			if (getInfo(ra.processName) == null) {
				continue;
			}

			Program pr = new Program();
			pr.setIcon(getInfo(ra.processName).loadIcon(packageManger));
			pr.setName(getInfo(ra.processName).loadLabel(packageManger).toString());
			pr.setPackageName(ra.processName);
			list.add(pr);
		}
		return list;
	}

	/**
	 * 通过一个程序名返回该程序的一个ApplicationInfo对象。
	 * 
	 * @param name
	 * @return ApplicationInfo
	 */
	public ApplicationInfo getInfo(String name) {
		if (name == null) {
			return null;
		}
		for (ApplicationInfo appinfo : appList) {
			if (name.equals(appinfo.processName)) {
				return appinfo;
			}
		}
		return null;
	}
}
